package com.cxc.kafka.demo.config;


import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class KafkaConfig {



    @Value("${spring.kafka.producer.bootstrap-servers}")
    private String bootstrap_servers_config;
    @Value("${spring.kafka.producer.retries}")
    private int retries_config;
    @Value("${spring.kafka.producer.batch-size}")
    private int batch_size_config;
    @Value("${spring.kafka.producer.properties.linger.ms}")
    private int linger_ms_config;
    @Value("${spring.kafka.producer.buffer-memory}")
    private int buffer_memory_config;


    @Bean
    public KafkaTemplate kafkaTemplate(){
        Map<String,Object> configs = new HashMap<>();
        configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrap_servers_config);
        configs.put(ProducerConfig.LINGER_MS_CONFIG,linger_ms_config);
        configs.put(ProducerConfig.RETRIES_CONFIG,retries_config);
        configs.put(ProducerConfig.BATCH_SIZE_CONFIG,batch_size_config);
        configs.put(ProducerConfig.BUFFER_MEMORY_CONFIG,buffer_memory_config);
        // 设置key value的序列化器
        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

//        // 指定自定义分区
//        configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, RoundRobinPartitioner.class);

        DefaultKafkaProducerFactory<String, String> kafkaProducerFactory = new DefaultKafkaProducerFactory<>(configs);
        return new KafkaTemplate(kafkaProducerFactory);
    }

}

